/**
  * @description: 字符串函数工具类
  * @author: lxz
  * @update: lxz(2021-01-18)
  */

/**
  * 转义,标签转义为字符
  * @param {string} str 需要转义的字符串
  * @return {string}    转义后的字符串
  */
export const translate = (str) => {
  var arrEntities = {
    '<': '&lt;',
    '>': '&gt;',
    ' ': '&nbsp;',
    '&': '&amp;',
    '"': '&quot;'
  }
  return str.replace(/(<|>| |&|")/ig, function (all, i) {
    return arrEntities[i]
  })
}

/**
  * 反转义，字符反转义为标签
  * @param {string} str 需要反转义的字符串
  * @return {string}    反转义后的字符串
  */
export const transferred = (str) => {
  var arrEntities = {
    lt: '<',
    gt: '>',
    nbsp: ' ',
    amp: '&',
    quot: '"',
    '#x2f': '/'
  }
  return str.replace(/&(lt|gt|nbsp|amp|quot|#x2f);/ig, function (all, i) {
    return arrEntities[i]
  })
}

/**
 * 获取字符串字节长度
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
  * 获取随机字符串
  * @param {number} len  长度
  * @return {string}     长度为len的随机字符串
  */
export function getRandomStr(len = 16) {
  const randomList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
  const keyList = []
  for (let i = 0; i < len; i++) {
    keyList.push(randomList[Math.round(Math.random() * (randomList.length - 1))])
  }
  return keyList.join('')
}

/**
 * 首字母大写
 * @param {String} string   转换字符串
 */
export function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

/**
 * 数字转汉字
 * @param {Number} num        转换的数字
 * @param {Boolean} capital   是否需要大写汉字
 * @return {String}           转换的文字
 */
export function numToChinese(num, capital = false) {
  const toggleObj = {
    1: { lower: '一', capital: '壹' },
    2: { lower: '二', capital: '貳' },
    3: { lower: '三', capital: '叁' },
    4: { lower: '四', capital: '肆' },
    5: { lower: '五', capital: '伍' },
    6: { lower: '六', capital: '陆' },
    7: { lower: '七', capital: '柒' },
    8: { lower: '八', capital: '捌' },
    9: { lower: '九', capital: '玖' },
    10: { lower: '十', capital: '拾' },
    100: { lower: '百', capital: '佰' },
    1000: { lower: '千', capital: '仟' }
  }
  return toggleObj[num][capital ? 'capital' : 'lower']
}
